package handler

import (
	"net/http"

	"go-file-perception-model/internal/logger"
	"go-file-perception-model/internal/model"
	"go-file-perception-model/internal/service"
	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

// IndexHandler 索引处理器
type IndexHandler struct {
	fileService *service.FileService
}

// NewIndexHandler 创建索引处理器实例
func NewIndexHandler(fileService *service.FileService) *IndexHandler {
	return &IndexHandler{
		fileService: fileService,
	}
}

// IndexFiles 处理文件索引请求
func (h *IndexHandler) IndexFiles(c *gin.Context) {
	var req model.IndexRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid request format",
			"error":   err.Error(),
		})
		return
	}

	// 验证请求参数
	if len(req.Directories) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "At least one directory must be specified",
		})
		return
	}

	// 调用服务层处理索引请求
	taskID, err := h.fileService.StartIndexing(req)
	if err != nil {
		logger.Error("Failed to start indexing", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to start indexing",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Indexing task started successfully",
		"data": gin.H{
			"task_id": taskID,
		},
	})
}

// GetIndexStatus 处理获取索引状态请求
func (h *IndexHandler) GetIndexStatus(c *gin.Context) {
	// 调用服务层获取索引状态
	status, err := h.fileService.GetIndexStatus()
	if err != nil {
		logger.Error("Failed to get index status", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to get index status",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Index status retrieved successfully",
		"data":    status,
	})
}

// GetIndexDirectories 处理获取索引目录列表请求
func (h *IndexHandler) GetIndexDirectories(c *gin.Context) {
	// 调用服务层获取索引目录列表
	directories, err := h.fileService.GetIndexDirectories()
	if err != nil {
		logger.Error("Failed to get index directories", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to get index directories",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Index directories retrieved successfully",
		"data":    directories,
	})
}

// AddIndexDirectory 处理添加索引目录请求
func (h *IndexHandler) AddIndexDirectory(c *gin.Context) {
	var req struct {
		Directory string `json:"directory" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid request format",
			"error":   err.Error(),
		})
		return
	}

	// 调用服务层添加索引目录
	if err := h.fileService.AddIndexDirectory(req.Directory); err != nil {
		logger.Error("Failed to add index directory", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to add index directory",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Index directory added successfully",
	})
}

// RemoveIndexDirectory 处理删除索引目录请求
func (h *IndexHandler) RemoveIndexDirectory(c *gin.Context) {
	var req struct {
		Directory string `json:"directory" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid request format",
			"error":   err.Error(),
		})
		return
	}

	// 调用服务层删除索引目录
	if err := h.fileService.RemoveIndexDirectory(req.Directory); err != nil {
		logger.Error("Failed to remove index directory", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to remove index directory",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Index directory removed successfully",
	})
}

// SetIndexDirectories 处理设置索引目录请求
func (h *IndexHandler) SetIndexDirectories(c *gin.Context) {
	var req struct {
		Directories []string `json:"directories" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid request format",
			"error":   err.Error(),
		})
		return
	}

	// 验证请求参数
	if len(req.Directories) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "At least one directory must be specified",
		})
		return
	}

	// 调用服务层设置索引目录
	if err := h.fileService.SetIndexDirectories(req.Directories); err != nil {
		logger.Error("Failed to set index directories", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to set index directories",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Index directories set successfully",
	})
}

// UpdateIndexDirectoryStatus 处理更新索引目录状态请求
func (h *IndexHandler) UpdateIndexDirectoryStatus(c *gin.Context) {
	var req struct {
		Directory string `json:"directory" binding:"required"`
		Enabled   bool   `json:"enabled" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid request format",
			"error":   err.Error(),
		})
		return
	}

	// 调用服务层更新索引目录状态
	if err := h.fileService.UpdateIndexDirectoryStatus(req.Directory, req.Enabled); err != nil {
		logger.Error("Failed to update index directory status", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to update index directory status",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Index directory status updated successfully",
	})
}

// ClearIndexChunks 处理清除索引分块请求
func (h *IndexHandler) ClearIndexChunks(c *gin.Context) {
	var req struct {
		Directory string `json:"directory"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"message": "Invalid request format",
			"error":   err.Error(),
		})
		return
	}

	// 调用服务层清除索引分块
	if err := h.fileService.ClearIndexChunks(req.Directory); err != nil {
		logger.Error("Failed to clear index chunks", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to clear index chunks",
			"error":   err.Error(),
		})
		return
	}

	message := "All index chunks cleared successfully"
	if req.Directory != "" {
		message = "Index chunks for directory '" + req.Directory + "' cleared successfully"
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": message,
	})
}

// ClearAllIndexChunks 处理清除所有索引分块请求
func (h *IndexHandler) ClearAllIndexChunks(c *gin.Context) {
	// 调用服务层清除所有索引分块
	if err := h.fileService.ClearIndexChunks(""); err != nil {
		logger.Error("Failed to clear all index chunks", zap.Error(err))
		c.JSON(http.StatusInternalServerError, gin.H{
			"success": false,
			"message": "Failed to clear all index chunks",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "All index chunks cleared successfully",
	})
}